import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:logger/logger.dart';
import 'package:sports_new/utils/date_time_utils.dart';
import 'package:sports_new/utils/utils.dart';
import '../../../controller/live/live_normal_logic.dart';
import '../../../controller/live/qkd_player_logic.dart';
import '../../../resources/colours.dart';
import '../../../resources/get_icon.dart';
import '../../../widgets/base/qkd_button.dart';
import '../../../widgets/base/qkd_text.dart';
import '../../match_detail/live/live_loading.dart';

class VerticalPanel extends StatefulWidget {
  const VerticalPanel({super.key, required this.logic});
  
  final LiveNormalLogic logic;

  @override
  State<VerticalPanel> createState() => _VerticalPanelState();
}

class _VerticalPanelState extends State<VerticalPanel> {
  Timer? countdown;
  DateTime? startTime;
  int? _countTime;
  bool notStart = false;
  bool _completion = false;
  final double barHeight = 72;

  late final QkdPlayerLogic playerLogic;
  
  int? get countTime => _countTime;
  set countTime(int? value) => setState(() => _countTime = value);

  bool get completion => _completion;
  set completion(bool value) => setState(() => _completion = value);

  @override
  void initState() {
    playerLogic = Get.find<QkdPlayerLogic>(tag: "${widget.logic.liveId}");
    startTime = DateTime.tryParse(
        widget.logic.liveDetail?.publishTime??""
    );
    if(startTime != null && widget.logic.waitStart){
      countTime = startTime!.difference(DateTime.now()).inSeconds;
      countdown = Timer.periodic(const Duration(seconds: 1), (timer) {
        countTime = countTime! - 1;
        if(countTime == 0 || !widget.logic.waitStart){
          timer.cancel();
        }
      });
    }
    super.initState();
  }

  void _playOrPause() {
    if (playerLogic.status == PlayStatus.started) {
      playerLogic.pause();
    } else if(playerLogic.status == PlayStatus.paused){
      playerLogic.pauseToPlay();
    }else{
      playerLogic.doRefresh();
    }
  }
  
  String secondsToHHMMSS(int seconds) {
    String formatTwoDigits(int n) => n.toString().padLeft(2, '0');

    final int hours = seconds ~/ 3600;
    seconds %= 3600;
    final int minutes = seconds ~/ 60;
    final int remainingSeconds = seconds % 60;

    return '${formatTwoDigits(hours)}时${formatTwoDigits(minutes)}分${formatTwoDigits(remainingSeconds)}秒';
  }

  @override
  Widget build(BuildContext context) {
    return GetBuilder<QkdPlayerLogic>(
      tag: "${widget.logic.liveId}",
      builder: (player) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onHorizontalDragStart: (details){
            if(playerLogic.duration != 0) {
              playerLogic.startSlide = true;
              playerLogic.onSlide = true;
              playerLogic.slidePosition =
                  playerLogic.currentPosition.toDouble();
            }
          },
          onHorizontalDragUpdate: (details){
            if(playerLogic.duration != 0) {
              Logger().d("${details.delta.dx / Get.width *
                  60000} 当前时长：${playerLogic.formTime()} 总时长：${playerLogic
                  .totalTime}");
              playerLogic.slidePosition += details.delta.dx / Get.width * 60000;
            }
          },
          onHorizontalDragEnd: (details) {
            if(widget.logic.liveDetail?.status == 2) {
              playerLogic.setPosition();
            }
          },
          child: Stack(
            alignment: Alignment.center,
            children: [
              if(countTime != null && countTime == 0 && !widget.logic.waitStart)
                const QkdText("主播正在赶来",color: Colours.white)
              else if(countTime != null && widget.logic.waitStart)
              QkdText(
                "距离${startTime?.formatedString("MM月dd日HH:mm")}直播开始还有\n"
                "${secondsToHHMMSS(countTime!)}",
                color: Colours.white,
                textAlign: TextAlign.center,
              )
              else if(playerLogic.status == PlayStatus.completion)
                Container(
                  alignment: Alignment.center,
                  color: Colours.black,
                  child: const QkdText(
                    "直播已结束",
                    color: Colours.white
                  )
                )
              else if(playerLogic.status == PlayStatus.idle || playerLogic.status == PlayStatus.prepared || playerLogic.status == PlayStatus.initialized)...[
                const Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    LiveLoading(
                      color: Colours.white,
                      size: 44,
                    ),
                    QkdText("加载中",color: Colours.white)
                  ],
                )
              ]else if(playerLogic.status == PlayStatus.error)...[
                Container(
                  alignment: Alignment.center,
                  color: Colours.black,
                  child: Column(
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Expanded(child: Container()),
                      const QkdText("视频加载失败，请稍后重试",color: Colours.white),
                      Container(height: 8),
                      QkdButton(
                        onPressed: playerLogic.doRefresh,
                        text: "重新连接",
                        width: 74,height: 30,
                        borderRadius: 6,
                        foregroundColor: Colours.main,
                        borderSide: const BorderSide(color: Colours.main,width: 0.5)
                      ),
                      Expanded(
                        child: Column(
                          mainAxisAlignment: MainAxisAlignment.end,
                          children: [
                            if(playerLogic.errorCode.hasValue)
                              QkdText(
                                "[${playerLogic.errorCode}]",
                                fontSize: 12,
                                color: Colors.white.withOpacity(0.5)
                              ),
                            Container(height: 8)
                          ],
                        )
                      )
                    ],
                  ),
                )
              ]else if(playerLogic.status == PlayStatus.completion)...[
                const QkdText("直播已结束",color: Colours.white)
              ]else if(playerLogic.status == PlayStatus.stopped)...[
                const QkdText("主播暂时离开，马上回来",color: Colours.white)
              ],
              if(playerLogic.startSlide??false)
                Positioned.fill(
                  child: Container(
                      color: Colours.black.withOpacity(0.8),
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Row(
                            mainAxisAlignment: MainAxisAlignment.center,
                            children: [
                              QkdText(
                                playerLogic.formTime(),
                                fontSize: 20,
                                color: Colours.main,
                                needCenter: true,
                              ),
                              Container(width: 4),
                              QkdText("/${playerLogic.totalTime}",
                                color: Colours.white,
                                needCenter: true,
                              ).paddingOnly(top: 5)
                            ],
                          ),
                          SizedBox(
                            width: 160,
                            child: LinearProgressIndicator(
                              minHeight: 2,
                              value: playerLogic.slidePosition/playerLogic.duration,
                              valueColor: const AlwaysStoppedAnimation<Color>(Colours.main),
                              backgroundColor: Colours.white.withOpacity(0.1),
                              borderRadius: BorderRadius.circular(13.5),
                            ),
                          )
                        ],
                      )
                  ),
                ),
              Column(
                children: [
                  const Spacer(),
                  if(playerLogic.duration != 0)
                  _buildBottomBar(context)
                ],
              )
            ],
          ),
        );
      }
    );
  }

  Widget _buildBottomBar(BuildContext context) {
    return Container(
      height: barHeight,
      padding: EdgeInsets.only(bottom: MediaQuery.of(Get.context!).orientation == Orientation.landscape?10:Get.mediaQuery.padding.bottom),
      decoration: BoxDecoration(
        gradient: LinearGradient(
          colors: [Colours.black.withOpacity(0.8),Colors.transparent],
          begin: Alignment.bottomCenter,end: Alignment.topCenter
        )
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.end,
        children: [
          SizedBox(
            height: 40,
            child: Row(
              children: <Widget>[
                IconButton(
                  onPressed: _playOrPause,
                  icon: Icon(
                    playerLogic.status == PlayStatus.paused?
                    GetIcon.pause:GetIcon.play,
                    color: Colours.white,
                    size: 24,
                  )
                ),
                QkdText(playerLogic.startSlide?playerLogic.formTime():playerLogic.positionTime,fontSize: 12,color: Colours.white),
                Container(width: 4),
                Expanded(child: slider()),
                Container(width: 4),
                QkdText(playerLogic.totalTime,fontSize: 12,color: Colours.white),
                Container(width: 16)
              ],
            ),
          ),
          Container(height: 10)
        ],
      ),
    );
  }

  Widget slider(){
    return SliderTheme(
      data: SliderTheme.of(context).copyWith(
        trackHeight: 2,
        trackShape: const RoundedRectSliderTrackShape(),
        activeTrackColor: Colours.main,
        inactiveTrackColor: Colours.white.withOpacity(0.25),
        thumbColor: Colours.white,
        thumbShape: const RoundSliderThumbShape(
            enabledThumbRadius: 6
        ),
        overlayShape: const RoundSliderOverlayShape(
            overlayRadius: 6
        ),
        overlayColor: Colours.white.withOpacity(0.5),
      ),
      child: Slider(
        value: playerLogic.startSlide?playerLogic.slidePosition:playerLogic.currentPosition.toDouble(),
        max: playerLogic.duration.toDouble(),
        allowedInteraction: SliderInteraction.tapAndSlide,
        onChangeStart: (value){
          playerLogic.startSlide = true;
          playerLogic.onSlide = true;
          playerLogic.slidePosition = value;
        },
        onChanged: (value)=> playerLogic.slidePosition = value,
        onChangeEnd: (value)=> playerLogic.setPosition(),
      ),
    );
  }
}
